/*
 * @Description: ------------ fileDescription -----------
 * @Author: snows_l snows_l@163.com
 * @Date: 2024-09-14 09:22:57
 * @LastEditors: snows_l snows_l@163.com
 * @LastEditTime: 2025-05-17 14:30:54
 * @FilePath: /BLOG/src/direvtive/loading.ts
 */
// 在你的 Vue 应用中的 directives.js 或类似文件
import Img from '@/assets/images/common/loading.svg';
import type { App } from 'vue';

type ParamsType = boolean | { value: boolean; style?: { [key: string]: string } };

function createLoading(el: HTMLElement, binging: ParamsType) {
  if (el.querySelector('#loading-view')) {
    el.removeChild(el.querySelector('#loading-view') as HTMLElement);
  }

  const show = typeof binging === 'boolean' ? binging : binging.value;
  if (!show) return false;

  // 创建 loading wrapper
  const loadingView = document.createElement('div');
  loadingView.id = 'loading-view';
  loadingView.style.position = 'absolute';
  loadingView.style.top = '50%';
  loadingView.style.left = '50%';
  loadingView.style.transform = 'translate(-50%, -50%)';
  loadingView.style.width = '100%';
  loadingView.style.height = '100%';
  loadingView.style.background = 'var(--bg-mask-color)';
  loadingView.style.zIndex = '99999999999';
  if (typeof binging === 'object' && binging.style) {
    for (const key in binging.style) {
      loadingView.style[key] = binging.style[key];
    }
  }

  // 创建 loading inner
  const loadingInner = document.createElement('div');
  loadingInner.style.position = 'absolute';
  loadingInner.style.top = '50%';
  loadingInner.style.left = '50%';
  loadingInner.style.transform = 'translate(-50%, -50%)';
  loadingInner.style.maxWidth = '140px';
  loadingInner.style.maxHeight = '170px';
  loadingInner.style.height = '80%';
  loadingInner.style.width = '80%';

  // 创建 loading img
  const img = document.createElement('img');
  img.src = Img;
  img.style.display = 'block';
  img.style.width = '100%';
  img.style.height = 'calc(100% - 30px)';

  // 创建 loading text
  const loadingText = document.createElement('p');
  loadingText.textContent = 'Loading...';
  loadingText.style.height = '30px';
  loadingText.style.lineHeight = '30px';
  loadingText.style.textAlign = 'center';
  loadingText.style.color = '#666';
  loadingText.style.fontSize = '18px';

  // 显示 loading
  loadingInner.appendChild(img);
  loadingInner.appendChild(loadingText);
  loadingView.appendChild(loadingInner);
  el.appendChild(loadingView);
}

const loadingDirective = {
  beforeMount(el: HTMLElement, binding: any) {
    el.style.setProperty('position', 'relative'); // 防止元素被覆盖
    createLoading(el, binding.value);
  },
  updated(el: HTMLElement, binding: any) {
    el.style.setProperty('position', 'relative'); // 防止元素被覆盖
    createLoading(el, binding.value);
  }
};

// 注册自定义指令
export default {
  install(app: App) {
    app.directive('loading', loadingDirective);
  }
};
